/** 
* @author : 褚国强
* @date 创建时间：2021年11月17日 上午9:18:21 
* @version 1.0
*/
package com.bsoft.project.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * @author : 褚国强
 * @date 创建时间：2021年11月17日 上午9:18:21
 * @Description: TODO
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public class RsfComIfsService {
//	private static final String url = "http://localhost:8097/fsi/api/rsfComIfsService/callService";
//	/** 按照报文要求传入JSON格式字符串 */
//	private static final String downInput = "{…}";
	
	private final static Logger logger = LoggerFactory.getLogger(RsfComIfsService.class);
	
	/**
	 * 
	 * @Description: 调用普通交易及文件下载交易
	 */
	public static void sentService(String url,String downInput,String filePath,String key,String secret) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		long currentTimeMillis = System.currentTimeMillis();
		String contentStr = currentTimeMillis + "\n" + downInput;
		String SHA256Str = currentTimeMillis + ":" + SignGenerator.encrytSHA256(contentStr, secret);
		httppost.setHeader("x-ca-key",key);
		httppost.setHeader("x-ca-signature", SHA256Str);
		logger.info("SHA256Str  contentStr------------- " + contentStr);
		logger.info("SHA256Str ------------- " + SHA256Str);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
		httppost.setConfig(requestConfig);
		ByteArrayEntity entity = new ByteArrayEntity(downInput.getBytes(StandardCharsets.UTF_8));
		entity.setContentType("text/plain");
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
			HttpEntity responseEntity = response.getEntity();
			String result;
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				result = EntityUtils.toString(responseEntity, "UTF-8");
				httppost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode + ",ERROR MSG: " + result);
			}
			if (responseEntity != null) {
				if (responseEntity.getContentType().getValue().contains("application/octet-stream")) {
					InputStream content = responseEntity.getContent();
					// 返回文件流
					File file = new File(filePath);
					FileOutputStream fileOutputStream = new FileOutputStream(file);
					int temp;
					while ((temp = content.read()) != -1) {
						fileOutputStream.write(temp);
					}
					fileOutputStream.close();
				} else {
					// 返回字符串
					result = EntityUtils.toString(responseEntity, "UTF-8");
					throw new RuntimeException("返回非文件流, 字符串: " + result);
				}
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			throw new RuntimeException("提交给服务器的请求，不符合HTTP协议", e);
		} catch (IOException e) {
			throw new RuntimeException("向服务器承保接口发起http请求,执行post请求异常", e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					throw new RuntimeException("response IOException: ", e);
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					throw new RuntimeException("httpclient IOException: ", e);
				}
			}
		}
	}
	/**
	 * 
	 * @Description: 解析json返回
	 */
	public static String sentServiceJson(String url,String downInput,String key,String secret,boolean isPrint) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		long currentTimeMillis = System.currentTimeMillis();
		String contentStr = currentTimeMillis + "\n" + downInput;
		String SHA256Str = currentTimeMillis + ":" + SignGenerator.encrytSHA256(contentStr, secret);
		httppost.setHeader("x-ca-key",key);
		httppost.setHeader("x-ca-signature", SHA256Str);
		if(isPrint){
			logger.info("SHA256Str  contentStr------------- " + contentStr);
			logger.info("SHA256Str ------------- " + SHA256Str);			
		}
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
		httppost.setConfig(requestConfig);
		ByteArrayEntity entity = new ByteArrayEntity(downInput.getBytes(StandardCharsets.UTF_8));
		entity.setContentType("text/plain");
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;

		String result = null;
		try {
			response = httpclient.execute(httppost);
			HttpEntity responseEntity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				result = EntityUtils.toString(responseEntity, "UTF-8");
				httppost.abort();
				if(!isPrint){
					logger.info("SHA256Str  contentStr------------- " + contentStr);
					logger.info("SHA256Str ------------- " + SHA256Str);			
				}
				throw new RuntimeException("HttpClient,error status code :" + statusCode + ",ERROR MSG: " + result);
			}
			if (responseEntity != null) {				
				// 返回字符串
				result = EntityUtils.toString(responseEntity, "UTF-8");
				if(isPrint){
					logger.info("sentServiceJson result: ------------- " + result);
				}
			}
			EntityUtils.consume(entity);
		} catch (ClientProtocolException e) {
			if(!isPrint){
				logger.info("SHA256Str  contentStr------------- " + contentStr);
				logger.info("SHA256Str ------------- " + SHA256Str);			
			}
			throw new RuntimeException("提交给服务器的请求，不符合HTTP协议", e);
		} catch (IOException e) {
			if(!isPrint){
				logger.info("SHA256Str  contentStr------------- " + contentStr);
				logger.info("SHA256Str ------------- " + SHA256Str);			
			}
			throw new RuntimeException("向服务器承保接口发起http请求,执行post请求异常", e);
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					if(!isPrint){
						logger.info("SHA256Str  contentStr------------- " + contentStr);
						logger.info("SHA256Str ------------- " + SHA256Str);			
					}
					throw new RuntimeException("response IOException: ", e);
				}
			}
			if (httpclient != null) {
				try {
					httpclient.close();
				} catch (IOException e) {
					if(!isPrint){
						logger.info("SHA256Str  contentStr------------- " + contentStr);
						logger.info("SHA256Str ------------- " + SHA256Str);			
					}
					throw new RuntimeException("httpclient IOException: ", e);
				}
			}			
		}
		return result;
	}
	/**
	 *  获取json 参数字符串
	 */
	public static String getParams(){
		Map<String,Object> params = new HashMap<String,Object>();
		return JSON.toJSONString(params);
	}
}
